package ysq.xyg.base.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * 把两张图片合并
 * @author lizhiyong
 * @version $Id: Pic.java, v 0.1
2015-6-3 下午3:21:23 1111 Exp $
 */
public class Pic {
    private Font       font     = new Font("宋体", Font.PLAIN, 22); // 添加字体的属性设置

    private Graphics2D g        = null;

    private int        fontsize = 0;

    private int        x        = 0;

    private int        y        = 0;
    private static Integer ROTATION_ANGLE =360; //弧度
    /**
     * 导入本地图片到缓冲区
     */
    public BufferedImage loadImageLocal(String imgName) {
        try {
            return ImageIO.read(new File(imgName));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * 导入网络图片到缓冲区
     */
    public BufferedImage loadImageUrl(String imgName) {
        try {
            URL url = new URL(imgName);
            return ImageIO.read(url);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * 生成新图片到本地
     */
    public void writeImageLocal(String newImage, BufferedImage img) {
        if (newImage != null && img != null) {
            try {
                File outputfile = new File(newImage);
                ImageIO.write(img, "jpg", outputfile);
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    /**
     * 设定文字的字体等
     */
    public void setFont(String fontStyle, int fontSize) {
        this.fontsize = fontSize;
        this.font = new Font(fontStyle, Font.PLAIN, fontSize);
    }

    /**
     * 修改图片,返回修改后的图片缓冲区（只输出一行文本）
     */
    public BufferedImage modifyImage(BufferedImage img, Object content, int x, int y,Color backgroundColor,Color fontColor) {

        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
            //去除毛边
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
            g.setBackground(backgroundColor);
            g.setColor(fontColor);//设置字体颜色
            if (this.font != null)
                g.setFont(this.font);
            // 验证输出位置的纵坐标和横坐标
            if (x >= w || y >= h) {
                this.x = h - this.fontsize + 2;
                this.y = w;
            } else {
                this.x = x;
                this.y = y;
            }
            if (content != null) {
                g.drawString(content.toString(), this.x, this.y);
            }
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return img;
    }

    /**
     * 修改图片,返回修改后的图片缓冲区（输出多个文本段） xory：true表示将内容在一行中输出；false表示将内容多行输出
     */
    public BufferedImage modifyImage(BufferedImage img, Object[] contentArr, int x, int y,
                                     boolean xory) {
        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
            g.setBackground(Color.WHITE);
            g.setColor(Color.RED);
            if (this.font != null)
                g.setFont(this.font);
            // 验证输出位置的纵坐标和横坐标
            if (x >= h || y >= w) {
                this.x = h - this.fontsize + 2;
                this.y = w;
            } else {
                this.x = x;
                this.y = y;
            }
            if (contentArr != null) {
                int arrlen = contentArr.length;
                if (xory) {
                    for (int i = 0; i < arrlen; i++) {
                        g.drawString(contentArr[i].toString(), this.x, this.y);
                        this.x += contentArr[i].toString().length() * this.fontsize / 2 + 5;// 重新计算文本输出位置
                    }
                } else {
                    for (int i = 0; i < arrlen; i++) {
                        g.drawString(contentArr[i].toString(), this.x, this.y);
                        this.y += this.fontsize + 2;// 重新计算文本输出位置
                    }
                }
            }
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return img;
    }

    /**
     * 修改图片,返回修改后的图片缓冲区（只输出一行文本）
     *
     * 时间:2007-10-8
     *
     * @param img
     * @return
     */
    public BufferedImage modifyImageYe(BufferedImage img) {

        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
            g.setBackground(Color.WHITE);
            g.setColor(Color.blue);//设置字体颜色
            if (this.font != null)
                g.setFont(this.font);
            g.drawString("www.hi.baidu.com?xia_mingjian", w - 85, h - 5);
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return img;
    }

    public BufferedImage modifyImagetogeter(BufferedImage b, BufferedImage d,int x,int y,int width,int height) {
        try {
            g = d.createGraphics();
            g.drawImage(b, x, y, width, height, null);
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return d;
    }
    /**
     * 图片圆形处理  返回处理后的图片
     * @param img  图片
     * @param width 宽
     * @param height 高
     * @param rotationAngle 弧度 
     * @param margin 边距 不传则不设置背景
     * @return
     * @throws Exception
     * 2017年3月12日
     * jianhui
     */
    public static BufferedImage getCircularImg(BufferedImage img,Integer width, Integer height,Integer rotationAngle,Integer margin,Color color){
        BufferedImage circularImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = circularImg.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(Color.WHITE);
        g2.fill(new RoundRectangle2D.Float(0, 0, width, height, rotationAngle,rotationAngle));
        g2.setComposite(AlphaComposite.SrcAtop);
        g2.drawImage(img, 0, 0, width, height, null);
        g2.dispose();
        if(margin!=null){
        circularImg = getCircularImgByBorder(circularImg, margin, color);
        }
        return circularImg;
    }

    /**
     * 圆形图片添加圆形背景
     * @param circularImg 传入的图
     * @param margin 边距
     * @param color 背景颜色
     * @return
     * @throws Exception
     * 2017年3月12日
     * jianhui
     */
    public static BufferedImage getCircularImgByBorder(BufferedImage circularImg, Integer margin, Color color){
        BufferedImage circularImgByBorder = new BufferedImage(circularImg.getWidth()+margin, circularImg.getHeight()+margin,circularImg.getType());
        Graphics2D g = circularImgByBorder.createGraphics();
        //去锯齿
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(color == null ? Color.WHITE : color);
        g.fill(new RoundRectangle2D.Float(0, 0, circularImg.getWidth()+margin, circularImg.getHeight()+margin, ROTATION_ANGLE,ROTATION_ANGLE));
        g.setComposite(AlphaComposite.SrcAtop);
        g.drawImage(circularImg, margin/2, margin/2,circularImg.getWidth(), circularImg.getHeight(), null);
        g.dispose();
        return circularImgByBorder;
    }

    public static boolean combinePic(String resultPic,String bgPic,String ewmPic,String logoPic,String nickName){
        Pic tt = new Pic();
        BufferedImage bgPics = acceptBufferdImage(bgPic);
        BufferedImage ewmPics = acceptBufferdImage(ewmPic);
        //获取圆形图片 //margin=null 则不设置图片背景
        //ewmPics = getCircularImg(ewmPics, 280, 280, 360, null, null);
        BufferedImage logoPics = tt.loadImageUrl(logoPic);
        //获取圆形图片 //margin=null 则不设置图片背景
        logoPics = getCircularImg(logoPics, 122, 122, 360, null, null);
        //生成二维码
        BufferedImage bgEwmPic=tt.modifyImagetogeter(ewmPics, bgPics,504, 646,148,148);
        if(bgEwmPic==null){
            return false;
        }
        //添加头像
        BufferedImage bgEwmLogoPic=tt.modifyImagetogeter(logoPics, bgEwmPic, 504,806,60,60);
        if(bgEwmLogoPic==null){
            return false;
        }
        //往图片上写文件，
        if(nickName.length() > 4){
            nickName=nickName.substring(0,3)+"...";
        }
        int a=0;
        int b=0;
        char[] c = nickName.toCharArray();
        for(int i = 0; i < c.length; i ++)
        {
            String len = Integer.toBinaryString(c[i]);
            if(len.length() > 8){
                a++;
            }else{
                b++;
            }
        }
        int xNum=332-a*11-b*6;
        BufferedImage bgEwmLogoTextPic=tt.modifyImage(bgEwmLogoPic, nickName, 574, 846,Color.BLACK,Color.BLACK);
        if(bgEwmLogoTextPic==null){
            return false;
        }
        tt.writeImageLocal(resultPic,bgEwmPic);
        return true;
    }

    public static boolean combineProductPic(String title,String price,String productPic,String resultPic,String bgPic,String ewmPic,String logoPic,String nickName){
        Pic tt = new Pic();
        BufferedImage bgPics = acceptBufferdImage(bgPic);
        BufferedImage ewmPics = acceptBufferdImage(ewmPic);
        //获取圆形图片 //margin=null 则不设置图片背景
        /*ewmPics = getCircularImg(ewmPics, 280, 280, 360, null, null);
        if(ewmPics==null){
            return false;
        }*/

        BufferedImage productPics = acceptBufferdImage(productPic);

        //生成二维码
        BufferedImage bgEwmPic=tt.modifyImagetogeter(ewmPics, bgPics,460, 790,160,160);
        if(bgEwmPic==null){
            return false;
        }
        //产品图片
        BufferedImage bgProductPic=tt.modifyImagetogeter(productPics, bgEwmPic,0, 80,658,658);
        if(bgProductPic==null){
            return false;
        }
        //添加头像
        BufferedImage logoPics = acceptBufferdImage(logoPic);
        //获取圆形图片 //margin=null 则不设置图片背景
        logoPics = getCircularImg(logoPics, 60, 60, 360, null, null);
        if(logoPics==null){
            return false;
        }
        BufferedImage bgEwmLogoPic=tt.modifyImagetogeter(logoPics, bgProductPic, 20,10,60,60);
        if(bgEwmLogoPic==null){
            return false;
        }
        //往图片上写昵称
        tt.font = new Font("宋体", Font.PLAIN, 30); // 添加字体的属性设置
        BufferedImage bgEwmLogoTextPic=tt.modifyImage(bgEwmLogoPic, nickName, 100, 55,Color.BLACK,Color.BLACK);
        if(bgEwmLogoTextPic==null){
            return false;
        }
        //往图片上写标题
        tt.font = new Font("宋体", Font.BOLD, 30); // 添加字体的属性设置
        BufferedImage bgTitleTextPic=tt.modifyImage(bgEwmLogoTextPic, title, 40, 780,Color.BLACK,Color.BLACK);
        if(bgTitleTextPic==null){
            return false;
        }

        //往图片上写符号
        /*tt.font = new Font("宋体", Font.PLAIN, 23); // 添加字体的属性设置
        BufferedImage bgFhTextPic=tt.modifyImage(bgTitleTextPic, "￥", 10, 118,Color.BLACK,Color.BLACK);
        if(bgFhTextPic==null){
            return false;
        }*/
        //往图片上写价格
        tt.font = new Font("宋体", Font.PLAIN, 35); // 添加字体的属性设置
        BufferedImage bgPrinceTextPic=tt.modifyImage(bgTitleTextPic, price, 65, 820,Color.RED,Color.RED);
        if(bgPrinceTextPic==null){
            return false;
        }
        tt.font = new Font("宋体", Font.PLAIN, 20); // 添加字体的属性设置
        BufferedImage bgPrinceTextF=tt.modifyImage(bgPrinceTextPic, "￥", 45, 820,Color.RED,Color.RED);
        if(bgPrinceTextF==null){
            return false;
        }

        tt.writeImageLocal(resultPic,bgPrinceTextF);
        return true;
    }

    public static BufferedImage acceptBufferdImage(String url){
        Pic tt = new Pic();
        if(url.startsWith("http")){
            return tt.loadImageUrl(url);
        }else{
            return tt.loadImageLocal(url);
        }
    }

    public static boolean combineBrandPic(String brandName,String time,String brandPic,String resultPic,String bgPic,String ewmPic,String logoPic,String nickName){
        Pic tt = new Pic();
        BufferedImage bgPics = acceptBufferdImage(bgPic);
        BufferedImage ewmPics = acceptBufferdImage(ewmPic);
        //获取圆形图片 //margin=null 则不设置图片背景
        ewmPics = getCircularImg(ewmPics, 280, 280, 360, null, null);
        if(ewmPics==null){
            return false;
        }
        BufferedImage logoPics = acceptBufferdImage(logoPic);
        //获取圆形图片 //margin=null 则不设置图片背景
        logoPics = getCircularImg(logoPics, 132, 132, 360, null, null);
        if(logoPics==null){
            return false;
        }
        BufferedImage brandPics = acceptBufferdImage(brandPic);
        //生成二维码
        BufferedImage bgEwmPic=tt.modifyImagetogeter(ewmPics, bgPics,316, 670,100,100);
        if(bgEwmPic==null){
            return false;
        }
        //品牌图片
        BufferedImage bgProductPic=tt.modifyImagetogeter(brandPics, bgEwmPic,0, 130,456,520);
        if(bgProductPic==null){
            return false;
        }
        //添加头像
        BufferedImage bgEwmLogoPic=tt.modifyImagetogeter(logoPics, bgProductPic, 40,670,100,100);
        if(bgEwmLogoPic==null){
            return false;
        }
        //往图片上写文件
        BufferedImage bgEwmLogoTextPic=tt.modifyImage(bgEwmLogoPic, nickName, 10, 500,Color.BLACK,Color.BLACK);
        if(bgEwmLogoTextPic==null){
            return false;
        }
        //往图片上写品牌
        tt.font = new Font("宋体", Font.PLAIN, 35); // 添加字体的属性设置
        BufferedImage bgBrandTextPic=tt.modifyImage(bgEwmLogoTextPic, brandName, 10, 40,Color.BLACK,Color.BLACK);
        if(bgBrandTextPic==null){
            return false;
        }
        //往图片上写时间
        tt.font = new Font("宋体", Font.PLAIN, 25); // 添加字体的属性设置
        BufferedImage bgTitleTextPic=tt.modifyImage(bgBrandTextPic, time, 10, 80,Color.BLACK,Color.GRAY);
        if(bgTitleTextPic==null){
            return false;
        }
        tt.writeImageLocal(resultPic,bgTitleTextPic);
        return true;
    }
    public static void main(String[] args) {
        Pic tt = new Pic();
        //总图片
        //combinePic("D:\\test\\result.jpg","D:\\test\\spBg.jpg","D:\\test\\1.png","http://thirdwx.qlogo.cn/mmopen/vi_32/PaE2icpFqo3HcFk1sV7h44B7VqibPGjv28AGFF2g46TS5VcIM6vT884icroSyvq6dgtspSVyUlicEZSgqMYaqCydKQ/132","萧邀人水电费水电费水电费等方式");
        //
        combineProductPic("大桃红","12.6","D:\\test\\pic.jpg","D:\\test\\pResult.jpg","D:\\test\\spBg.jpg","D:\\test\\ewm.jpg","http://thirdwx.qlogo.cn/mmopen/vi_32/PaE2icpFqo3HcFk1sV7h44B7VqibPGjv28AGFF2g46TS5VcIM6vT884icroSyvq6dgtspSVyUlicEZSgqMYaqCydKQ/132","萧邀人");

        /*BufferedImage bgPic = tt.loadImageLocal("D:\\test\\spBg.jpg");
        BufferedImage ewmPic = tt.loadImageLocal("D:\\test\\1.png");
        //获取圆形图片 //margin=null 则不设置图片背景
        ewmPic = getCircularImg(ewmPic, 80, 80, 360, null, null);
        BufferedImage productPic = tt.loadImageLocal("D:\\test\\2.jpg");
        BufferedImage logoPic = tt.loadImageUrl("http://thirdwx.qlogo.cn/mmopen/vi_32/0icicabQPFRfiayVQ8ySCxzdTibVKGM1D3Zht8ubyL6Z9EBWrNL88O1kk9rnCHS7ibQAs15AibibmZRBxR5DsujBKicaXg/132");
        //获取圆形图片 //margin=null 则不设置图片背景
        logoPic = getCircularImg(logoPic, 80, 80, 360, null, null);
        //生成二维码
        BufferedImage bgEwmPic=tt.modifyImagetogeter(ewmPic, bgPic,336, 660,80,80);
        //产品图片
        BufferedImage bgProductPic=tt.modifyImagetogeter(productPic, bgEwmPic,0, 130,800,520);
        //添加头像
        BufferedImage bgEwmLogoPic=tt.modifyImagetogeter(logoPic, bgProductPic, 40,660,80,80);
        //往图片上写文件
        BufferedImage bgEwmLogoTextPic=tt.modifyImage(bgEwmLogoPic, "萧邀人", 10, 780,Color.WHITE,Color.WHITE);
        //往图片上写品牌
        tt.font = new Font("宋体", Font.PLAIN, 35); // 添加字体的属性设置
        BufferedImage bgBrandTextPic=tt.modifyImage(bgEwmLogoTextPic, "萧邀", 10, 40,Color.BLACK,Color.BLACK);
        //往图片上写标题
        tt.font = new Font("宋体", Font.PLAIN, 25); // 添加字体的属性设置
        BufferedImage bgTitleTextPic=tt.modifyImage(bgBrandTextPic, "安踏鞋子", 10, 80,Color.BLACK,Color.GRAY);
        //往图片上写符号
        tt.font = new Font("宋体", Font.PLAIN, 23); // 添加字体的属性设置
        BufferedImage bgFhTextPic=tt.modifyImage(bgTitleTextPic, "￥", 10, 118,Color.BLACK,Color.BLACK);

        //往图片上写价格
        tt.font = new Font("宋体", Font.PLAIN, 35); // 添加字体的属性设置
        BufferedImage bgPrinceTextPic=tt.modifyImage(bgFhTextPic, "39.5", 35, 120,Color.BLACK,Color.BLACK);

        tt.writeImageLocal("D:\\test\\bg2.png",bgPrinceTextPic);*/
        //将多张图片合在一起
        System.out.println("success");
    }
}
